package com.txw.javaCore.server.elasticJob;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.dataflow.DataflowJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @PROJECT_NAME: JavaCoreB2
 * @DESCRIPTION: ElasticJob - 底层执行原理 -步骤一：fetchData 步骤二：processData
 * @Author: 涂玄武
 * @DATE: 2021/3/14 15:43
 */
@Component
@Slf4j
public class ElasticJobBlogImage implements DataflowJob<String> {

    @Autowired
    private Environment env;

    @Autowired
    private BlogImageService blogImageService;

    /**
     * 拉数据:先分片、对应着多个线程，去DB拉取数据
     *
     * @param shardingContext
     * @return
     */
    @Override
    public List<String> fetchData(ShardingContext shardingContext) {
        /**
         * 嵌入到SQL语句中：
         * AND MOD(C.ID,#{total}) IN (#{item})
         */
        //总切片数
        Integer total = shardingContext.getShardingTotalCount();
        //切片项
        Integer item = shardingContext.getShardingItem();
        //额外的查询条件
        /**
         * 嵌入到SQL语句中：
         * <if test = "params!=null and params!=''">
         *     ${params}
         * </if>
         */
        String queryParam = shardingContext.getShardingParameter();


        log.info("-- Elastic Job开启：{} ,总分片数：{},分片项：{},自定义的查询参数：{}--", shardingContext.getJobName(), total, item, queryParam);

        //模拟数据库查询数据
        //blogImageMapper.selectDeletedImageJob(env.getProperty("common.file.upload.root.url"),queryParam,total,item)
        List<String> list = new ArrayList<>();
        list.add(env.getProperty("common.file.upload.root.url") + "1.jpg");
        list.add(env.getProperty("common.file.upload.root.url") + "2.jpg");
        list.add(env.getProperty("common.file.upload.root.url") + "3.jpg");
        list.add(env.getProperty("common.file.upload.root.url") + "4.jpg");

        return list;
    }

    /**
     * 处理数据
     *
     * @param shardingContext
     * @param list
     */
    @Override
    public void processData(ShardingContext shardingContext, List<String> list) {
        log.info("-- Elastic Job开启：{} ,当前分片项：{}，拉取到的数据：{}--", shardingContext.getJobName(), shardingContext.getShardingItem(), list);
        if (!CollectionUtils.isEmpty(list)){
            blogImageService.commonCleanImage(list);
        }
    }
}
